<template>
  <el-container class="app-container">
    <!--表格-->
    <el-page-header @back="$router.go(-1)" content="房源详情"></el-page-header>
    <el-card class="box-card">


      <div slot="header" class="clearfix  box-card-h">
        <span>{{room.areaName}}  {{room.buildingNo}}幢/ {{room.buildingFloor}}楼/ {{room.roomNo}}室</span>
<!--        <el-button style="float: right; padding: 5px 0" type="text">编辑房源信息</el-button>-->
      </div>
      <div>
        <el-row class="p-style">
          <span class="p-r-15">面积(㎡)：{{room.measureArea}}</span>
          <span class="p-r-15">装修：{{$filter('zxStyle',room.decorationStyle)}} </span>
          <span class="p-r-15">预租单价：{{room.rentPrice}}{{$filter('priceUnit',room.priceUnit)}}</span>
          <span class="p-r-15">状态：{{$filter('zsStatus',room.status)}}</span>
          <span class="p-r-15">房源备注：{{room.remark}}</span>
        </el-row>
      </div>
    </el-card>

    <el-card class="box-card">
      <div slot="header" class="clearfix  box-card-h">
        <span>租赁效益</span>
      </div>
      <table-view
        :columns="tableContentzlxy"
        :pageList="columnDatabzlxy"
      >
      </table-view>
    </el-card>


    <el-card class="box-card">
      <div slot="header" class="clearfix box-card-h">
        <span>租户</span>
        <router-link :to="{name:'addContract',query:{id:$route.query.id,roomDetail:$route.query.roomDetail}}">
          <el-button style="float: right; padding: 8px" icon="el-icon-plus" type="warning">合同</el-button>
        </router-link>
      </div>
      <table-view
        :columns="tableContentzh"
        :pageList="columnDatazh"
        :templateDiv="{operation:true}"
      >
        <template slot="operation" slot-scope="scope">
          <router-link :to="{name:'contractDetail',query:{id:columnDatazh[0].id,roomDetail:$route.query.roomDetail}}">
          <el-button size="mini" type="text">合同详情</el-button>
          </router-link>
        </template>
      </table-view>

      <h5>合同标签</h5>
      <el-tag
        class="tags m-r-10"
        v-for="(item,i) in contractLabelIds"
        :key="i"
        type="success"
        effect="dark"
      >
        {{ item }}
      </el-tag>
    </el-card>


    <el-card class="box-card">
      <div slot="header" class="clearfix box-card-h">
        <span>增值服务收益</span>
        <el-button style="float: right; padding: 8px" icon="el-icon-plus" type="warning" @click="addBenify">补录</el-button>
      </div>
      <table-view
        :columns="tableContentzzfwsy"
        :pageList="columnDatazzfwsy"
        :templateDiv="{operation:true}"
      >
        <template slot="operation" slot-scope="scope">
          <el-button size="mini" type="text" @click="editBtnClick(scope.row ,'benifitView')">收益明细</el-button>
        </template>
      </table-view>

      <h5>服务标签</h5>
      <el-tag
        class="tags m-r-10"
        v-for="(item,i) in serviceGainLabelIds"
        :key="i"
        type="success"
        effect="dark">
        {{ item }}
      </el-tag>
    </el-card>
    <el-footer></el-footer>


    <el-dialog title="收益明细" :visible.sync="dialogAddDetail" width="60%"
               :destroy-on-close="true">
      <!--表格-->
      <table-view
        :columns="tableContentsymx"
        :pageList="columnDatasymx"
        :templateDiv="{labelIds:true}"
      >
        <template slot="labelIds" slot-scope="scope">
          {{scope.row.labelIds}}
          <el-tag
            class="tags"
            v-for="(item,i) in scope.row.labelIds"
            :key="i"
            :type="success"
            effect="dark">
            {{ item.labelName }}
          </el-tag>
        </template>
      </table-view>
      <!--分页-->
      <div style="padding-bottom: 60px">
        <pagination-view
          :pagesize="gainPage.pageSize"
          :currentPage="gainPage.pageNumber"
          :total="gainPageTotal"
          @size-change="gainSizeChange"
          @current-change="gainPageChange"
        ></pagination-view>
      </div>
    </el-dialog>


    <el-dialog title="添加收益信息" :visible.sync="dialogAddBenify" width="60%"
               :destroy-on-close="true">
      <el-form ref="form" :model="formBenify" :rules="rules" label-width="120px" style="width: 90%">
        <el-form-item prop="labelName" label="服务标签:">
          <el-select
                  style="width: 400px"
                  v-model="formBenify.labelId"
                  multiple
                  placeholder="请选择">
            <el-option
                    v-for="(item,i) in severLabels"
                    :key="i"
                    :label="item.labelName"
                    :value="item.id">
            </el-option>
          </el-select>
          <el-button type="" size="mini" icon="el-icon-plus" @click="addLabel">新增标签</el-button>
        </el-form-item>
        <el-form-item prop="gainType" label="收/支:">
          <el-radio-group v-model="formBenify.gainType">
            <el-radio label="1">收入金额</el-radio>
            <el-radio label="-1">支出金额</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="price" label="金额（元):">
          <el-input v-model.trim="formBenify.price" type="number"></el-input>
        </el-form-item>
        <el-form-item prop="remark" label="备注:">
          <el-input v-model.trim="formBenify.remark" type="textarea"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmitAddBenify">保存</el-button>
        </el-form-item>
      </el-form>

      <el-dialog title="新增标签" :visible.sync="dialogAddLabel" width="60%"
                 :destroy-on-close="true" append-to-body>
        <el-form ref="form" :model="formLabel" :rules="rules" label-width="120px" style="width: 90%">
          <el-form-item prop="labelName" label="标签名称:">
            <el-input v-model.trim="formLabel.labelName"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmitLabel">保存</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-dialog>



  </el-container>
</template>

<script>
  import TableView from '@/components/TableView'
  import * as commonApi from '@/api/common'


  import PaginationView from '@/components/PaginationView'
  import * as pageApi from '@/api/spaceBusiness/houseManage'

  export default {
    name: 'list',
    components: {
      TableView,
      PaginationView,
    },
    data() {
      return {
        dialogAddBenify:false,
        formBenify:{
          "gainType": '',
          "labelId": "",
          "price": '',
          "remark": "",
          "roomId": '',
          "tenantryId": ''
        },
        formLabel:{
          labelName:'',
        },
        severLabels:[],
        dialogAddLabel:false,

        room:{},
        contractLabelIds:[],
        serviceGainLabelIds:[],
        dialogAddDetail:false,
        columnDatasymx: [],
        gainPage: {
          pageNumber: 1,
          pageSize: 20,
          roomId: '',
        },
        gainPageTotal: 0,
        tableContentsymx: [{
          field: 'tenantryName',
          label: '租户主体'
        }, {
          field: 'labelIds',
          label: '服务项'
        }, {
          field: 'price',
          label: '金额（收入/支出）'
        }, {
          field: 'operator',
          label: '来源（操作人）'
        }, {
          field: 'createdTime',
          label: '时间'
        }, {
          field: 'remark',
          label: '备注'
        }],


        dialogTitle: '添加',
        dialogVisible: false,
        dialogType: 'add',
        tableContentzlxy: [{
          field: 'rentPercent',
          label: '出租率'
        }, {
          field: 'vacantDate',
          label: '空置起算日',
        }, {
          field: 'vacantDays',
          label: '空置天数',
        }, {
          field: 'rentedDays',
          label: '已租出天数',
        }],
        tableContentzh: [{
          field: 'lesseeName',
          label: '租户主体'
        }, {
          field: 'followerName',
          label: '跟进人',
        }, {
          field: 'measureArea',
          label: '租赁面积（㎡）',
        }, {
          field: 'rentalDate',
          label: '计租日',
        }, {
          field: 'rentalDueDate',
          label: '结束日',
        }, {
          field: 'contractPrice',
          label: '合同单价',
        }, {
          field: 'timelyPrice',
          label: '实时单价',
        }, {
          field: 'securityMoney',
          label: '保证金（元）',
        }, {
          field: 'rentalMoney',
          label: '租金（元)',
        }, {
          field: 'status',
          label: '状态',
        },{
          field: 'operation',
          label: '操作',
        }],
        tableContentzzfwsy: [{
          field: 'lesseeName',
          label: '租客主体'
        }, {
          field: 'incomeAmount',
          label: '累计收入',
        }, {
          field: 'expendAmount',
          label: '累计支出',
        }, {
          field: 'total',
          label: '小计',
        },{
          field: 'operation',
          label: '操作',
        }],
        contract:{},
        serviceGain:{},
        columnDatabzlxy: [],
        columnDatazh: [],
        columnDatazzfwsy: [],
        customWidth: '',
        pageInfo: {
          pageNum: 1,
          pageSize: 20,
          title: ''
        },
        total: 0,
        form: {
          costAmount: '',
          intro: '',
          memo: '',
          title: '',
          addressDetail: '',
          addressName: '',
          saleAmount: '',
          sort: ''
        },
        rules: {
          gainType: { required: true, trigger: 'blur', message: '类型不能为空' },
          price: { required: true, trigger: 'blur', message: '金额不能为空' },
          labelId: { required: true, trigger: 'blur', message: '标签不能为空' },


          labelName: { required: true, trigger: 'blur', message: '名称不能为空' },
          productName: [
            {required: true, trigger: 'blur', message: '名称不能为空'},
            {min: 1, max: 14, message: '长度不能超过14个汉字'}
          ],
          intro: [
            {required: true, trigger: 'blur', message: '简介不能为空'},
            {min: 1, max: 20, message: '长度不能超过20个汉字'}
          ],
          durationTime: [{required: true, trigger: 'change', message: '请选择套餐时长'}],
          sort: [{required: true, trigger: 'blur', message: '请填写排序'}],
          enable: [{required: true, trigger: 'change', message: '请选择套餐状态'}],
          tag: [{min: 1, max: 4, trigger: 'blur', message: '长度不能超过4个汉字'}],
        }
      }
    },
    watch: {},
    methods: {
      addBenify(){
        this.formBenify = {
          "gainType": '',
          "labelId": "",
          "price": '',
          "remark": "",
          "roomId": '',
          "tenantryId": ''
        }
        this.formBenify.tenantryId = this.serviceGain.tenantryId
        this.formBenify.roomId = this.room.id
        this.dialogAddBenify = true
      },
      onSubmitAddBenify(){
        console.log(this.formBenify);
        let post = Object.assign({},this.formBenify)
        post.labelId = post.labelId.join(',')
        pageApi.addGain(post).then(res=>{
          this.handleMessage(res)
          if(res.code === '200'){
            this.dialogAddBenify = false
            this.init()
          }
        })
      },
      addLabel(){
        this.formLabel = {
          labelName:'',
          labelType:1
        }
        this.dialogAddLabel = true
      },
      onSubmitLabel(){
        commonApi.addLabel(this.formLabel).then(res=>{
          this.handleMessage(res)
          if(res.code === '200'){
            this.dialogAddLabel = false
            this.getAllLabel()
          }
        })
      },
      getGain() {
        this.dialogAddDetail = true
        pageApi.getGain(this.gainPage).then(res => {
          this.columnDatasymx = res.body.objects
          this.gainPageTotal = Number(res.body.recordTotal)
          this.gainPage.pageNumber = Number(res.body.pageNumber) || 1

        })
      },
      gainSizeChange(val) {
        this.gainPage.pageSize = val
        this.getGain()
      },
      gainPageChange(val) {
        this.gainPage.pageNumber = val
        this.getGain()
      },
      editBtnClick(row,type){
        switch (type) {
          case 'benifitView':
            this.getGain()
                break
        }
      },

      addOne() {
        this.dialogVisible = true
        this.dialogTitle = '添加'
      },

      onSubmit() {
        let form = this.form
        let dialogType = this.dialogType
        form.duration = form.durationTime + (form.productTypeId == 1 ? '个月' : '天')
        form.enable = Number(form.enable)
        this.$refs['form'].validate((valid) => {
          if (valid) {
            switch (dialogType) {
              case 'add':
                this.dialogTitle = '添加'
                pageApi.create(form).then(res => {
                  this.handleRes(res)
                })
                break
              case 'update':
                this.dialogTitle = '编辑'
                pageApi.update(form).then(res => {
                  this.handleRes(res)
                })
                break
            }
          }
        })
      },
      handleRes(res) {
        this.handleMessage(res)
        if (res.code === '200') {
          this.dialogVisible = false
          this.getData()
        }
      },
      // pageSize变化函数
      sizeChange(val) {
        this.pageInfo.pageSize = val
        this.getData()
      },
      // page变化函数
      pageChange(val) {
        this.pageInfo.pageNumber = val
        this.getData()
      },

      //拉取列表
      getData() {
        pageApi.getList(this.pageInfo).then(res => {
          this.columnData = res.body.records
          this.total = Number(res.body.total)
          this.pageInfo.pageNumber = Number(res.body.pageNumber) || 1
        })
      },
      getAllLabel(){
        //服务标签
        commonApi.getAllLabel(1).then(res=>{
          this.severLabels = res.body
        })
      },
      handleClose(done) {
        let resetForm = {
          costAmount: '',
          courseProductId: '',
          duration: '',
          durationTime: '',
          enable: true,
          intro: '',
          memo: '',
          productName: '',
          saleAmount: '',
          sort: '',
          tag: ''
        }
        this.form = Object.assign({}, this.form, resetForm)
        done()
      },
      init(){
        let {id} = this.$route.query
        this.gainPage.roomId = id
        pageApi.getById(id).then(res => {
          this.columnDatabzlxy = [res.body.benefit]
          this.contract = res.body.contract
          this.serviceGain = res.body.serviceGain
          this.columnDatazh = res.body.contract&&[this.contract]

          this.columnDatazzfwsy = res.body.serviceGain&&[this.serviceGain]
          //
          this.room = res.body.room
          this.contractLabelIds = this.contract&&this.contract.labelIds || []
          this.serviceGainLabelIds = this.serviceGain&&this.serviceGain.labelIds || []
        })
      }

    },
    mounted() {
      this.init()
      this.getAllLabel()
    }
  }
</script>

<style lang="scss" scoped>
  .p-style {
    font-pageSize: 14px;
  }

  .box-card {
    margin-top: 15px;
    .box-card-h {
      font-pageSize: 16px;
      font-weight: 500;
    }
  }
</style>
